package com.fbs.wowo.wx.web;

import com.fbs.wowo.base.Response;
import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.util.common.ComUtils;
import com.fbs.wowo.util.common.Constants;
import com.fbs.wowo.wx.entity.WxAuth;
import com.fbs.wowo.wx.entity.WxBinding;
import com.fbs.wowo.wx.entity.WxEntity;
import com.fbs.wowo.wx.mapper.WxAuthMapper;
import com.fbs.wowo.wx.mapper.WxBindingMapper;
import com.fbs.wowo.wx.mapper.WxEntityMapper;
import com.fbs.wowo.wx.service.AccessTokenService;
import com.fbs.wowo.wx.service.PreAuthCodeService;
import com.fbs.wowo.wx.wxUtil.HttpUtils;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WxOaInfoController {

    @Resource
    private WxEntityMapper wxEntityMapper;

    @Resource
    private WxBindingMapper wxBindingMapper;

    @Resource
    private AccessTokenService accessTokenService;

    @Resource
    private PreAuthCodeService preAuthCodeService;

    @Resource
    private WxAuthMapper wxAuthMapper;


    @GetMapping("/wx/auth")
    @ResponseBody
    public Response auth() {

        System.out.println("进入auth!");

        Map map = new HashMap<>();
        map.put("appId", TicketController.appId);
        map.put("preAuthCode", preAuthCodeService.getPreAuthCode());
        map.put("redirectUri", Constants.getURL() + "/authresult");
        return Response.success(map);
    }


    @GetMapping("/authresult")
    public String authPage(HttpServletRequest request) {

        System.out.println("进入authresult!");

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("uuQieKeNaoId")) {
                String userId = cookie.getValue();
                String auth_code = request.getParameter("auth_code");
                String expires_in = request.getParameter("expires_in");
                long l = System.currentTimeMillis() + (Long.parseLong(expires_in) * 1000);
                WxBinding wb = wxBindingMapper.findByUserId(userId);
                if (wb != null) {
                    throw new DataOverflowException(ErrorCode.ERR_HAVE_AUTH);
                }
                WxBinding wxBinding = new WxBinding();
                wxBinding.setId(ComUtils.getUUID());
                wxBinding.setUserId(userId);
                wxBinding.setAuthCode(auth_code);
                wxBinding.setAuthCodeExpirationTime(l);
                wxBindingMapper.insertSelective(wxBinding);

                System.out.println("cookies:");
                System.out.println("userId:" + userId);
                System.out.println("auth_code:" + auth_code);
                System.out.println("expires_in:" + expires_in);
                return "redirect:" + Constants.getURL() + "/wx_list.html";
            }
        }
        throw new DataOverflowException(ErrorCode.ERR_COOKIE_NULL);
    }


    /**
     * @param type
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping("/wx/list")
    @ResponseBody
    public Response list(String type, int pageNum, int pageSize, String userId) throws Exception {
        System.out.println("进入list!");

        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="
                + getWxAuthorizerAccessToken(userId);
        Map<String, String> map = new HashMap<>();
        map.put("type", type);
        map.put("offset", String.valueOf((pageNum - 1) * pageSize));
        map.put("count", String.valueOf(pageSize));
        JSONObject jsonParam = JSONObject.fromObject(map);
        String returnData = HttpUtils.post(url, jsonParam.toString());
        String data = new String(returnData.getBytes("ISO8859-1"), "UTF-8");

        System.out.println("data:" + data);

        JSONObject json = JSONObject.fromObject(data);
        if (json.containsKey("item")) {
            JSONArray item = json.getJSONArray("item");
            for (int i = 0; i < item.size(); i++) {
                JSONObject jsonObject = item.getJSONObject(i);
                JSONArray jsonArray = jsonObject.getJSONObject("content").getJSONArray("news_item");
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jo = jsonArray.getJSONObject(j);
                    String mediaId = (String) jo.get("thumb_media_id");
                    WxAuth wxAuthState = wxAuthMapper.findWxAuthState(userId, mediaId);
                    if (wxAuthState == null) {
                        jo.put("state", 1);         //没确权
                    } else {
                        jo.put("state", 2);         //已确权
                    }
                }
            }
            PageHelper.startPage(pageNum, pageSize);
            return Response.success(json);
        }
        throw new DataOverflowException(ErrorCode.ERR_JSON_PARSING);
    }

    @GetMapping("/wx/info")
    @ResponseBody
    public Response info(String userId) throws Exception {

        System.out.println("进入info!");

        WxEntity wx = wxEntityMapper.selectByPrimaryKey(1);
        if (wx != null) {
            String infoUrl = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token="
                    + accessTokenService.getWxAccessToken();
            HashMap<Object, Object> map = new HashMap<>();
            map.put("component_appid", TicketController.appId);
            getWxAuthorizerAccessToken(userId);
            WxBinding wb = wxBindingMapper.findByUserId(userId);
            if (wb != null) {
                map.put("authorizer_appid", wb.getAuthorizerAppid());
                JSONObject infoJson = JSONObject.fromObject(map);
                String infoData = HttpUtils.post(infoUrl, infoJson.toString());
                String info = new String(infoData.getBytes("ISO8859-1"), "UTF-8");
                JSONObject json = JSONObject.fromObject(info);

                System.out.println("infoData:" + info);

                return Response.success(json);
            }
            throw new DataOverflowException(ErrorCode.ERR_USER_NULL_BD);
        }
        throw new DataOverflowException(ErrorCode.ERR_WXENTITY_NULL);
    }

    @PostMapping("/wx/remove")
    @ResponseBody
    public Response remove(String userId) {
        System.out.println("进入解除绑定!");

        WxBinding wb = wxBindingMapper.findByUserId(userId);
        if (wb != null) {
            wxBindingMapper.deleteByPrimaryKey(wb.getId());
            return Response.success();
        }
        throw new DataOverflowException(ErrorCode.ERR_USER_NULL_BD);
    }


    /**
     * 获取AuthorizerAccessToken
     *
     * @return
     */
    public String getWxAuthorizerAccessToken(String userId) {

        System.out.println("进入获取授权者的token!");

        WxBinding wb = wxBindingMapper.findByUserId(userId);
        if (wb != null) {
            if (wb.getAuthorizerAccessToken()!=null &&!wb.getAuthorizerAccessToken().equals("")){
                if (wb.getAatExpirationTime() != null && !wb.getAatExpirationTime().equals("")) {
                    if (System.currentTimeMillis() < wb.getAatExpirationTime()) {
                        System.out.println("这是已保存的token");
                        return wb.getAuthorizerAccessToken();
                    }
                    return refreshAuthorizerAccessToken(wb);
                }
            }
            return getAuthorizerAccessToken(wb);
        }
        throw new DataOverflowException(ErrorCode.ERR_USER_NOT_EXIST);
    }

    public String getAuthorizerAccessToken(WxBinding wb) {
        System.out.println("进入创建授权者的token!");

        String url =
                "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="
                        + accessTokenService.getWxAccessToken();
        Map<String, String> map = new HashMap<>();
        map.put("component_appid", TicketController.appId);
        if (wb.getAuthCode() != null && !wb.getAuthCode().equals("")) {
            map.put("authorization_code", wb.getAuthCode());
            JSONObject jsonParam = JSONObject.fromObject(map);
            String returnData = HttpUtils.post(url, jsonParam.toString());
            System.out.println("getAuthorizerAccessToken:\n" + returnData + "\n\n");
            JSONObject json = JSONObject.fromObject(returnData);
            if (json.containsKey("authorization_info")) {
                if (json.get("authorization_info") != null && !json.get("authorization_info").equals("")) {
                    wb.setAatExpirationTime(System.currentTimeMillis() + (Integer.parseInt(json.getJSONObject("authorization_info").get("expires_in").toString()) * 1000));
                    wb.setAuthorizerAccessToken(json.getJSONObject("authorization_info").get("authorizer_access_token").toString());
                    wb.setAuthorizerRefreshToken(json.getJSONObject("authorization_info").get("authorizer_refresh_token").toString());
                    wb.setAuthorizerAppid(json.getJSONObject("authorization_info").get("authorizer_appid").toString());
                    wxBindingMapper.updateByPrimaryKeySelective(wb);

                    System.out.println("创建的token:" + json.getJSONObject("authorization_info").get("authorizer_access_token").toString());

                    return json.getJSONObject("authorization_info").get("authorizer_access_token").toString();
                }
            }
            throw new DataOverflowException(ErrorCode.ERR_WX_AAT_NULL);
        }
        throw new DataOverflowException(ErrorCode.ERR_AUTHCODE_NULL);
    }


    /**
     * 刷新accessToken
     *
     * @return
     */
    public String refreshAuthorizerAccessToken(WxBinding wb) {

        System.out.println("进入刷新授权者的token!");

        String url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token="
                + accessTokenService.getWxAccessToken();
        HashMap<String, String> map = new HashMap<>();
        map.put("component_appid", TicketController.appId);
        if (wb.getAuthorizerAppid() != null && !wb.getAuthorizerAppid().equals("")) {
            map.put("authorizer_appid", wb.getAuthorizerAppid());
            map.put("authorizer_refresh_token", wb.getAuthorizerRefreshToken());
            JSONObject jsonParam = JSONObject.fromObject(map);
            String returnData = HttpUtils.post(url, jsonParam.toString());
            System.out.println("refreshAuthorizerAccessToken:\n" + returnData + "\n\n");
            JSONObject json = JSONObject.fromObject(returnData);
            if (json.containsKey("authorizer_access_token")) {
                if (json.get("authorizer_access_token") != null && !json.get("authorizer_access_token").equals("")) {
                    wb.setAatExpirationTime(System.currentTimeMillis() + (Integer.parseInt(json.get("expires_in").toString()) * 1000));
                    wb.setAuthorizerAccessToken(json.get("authorizer_access_token").toString());
                    wb.setAuthorizerRefreshToken(json.get("authorizer_refresh_token").toString());
                    wxBindingMapper.updateByPrimaryKeySelective(wb);

                    System.out.println("刷新过的token!" + json.get("authorizer_access_token").toString());

                    return json.get("authorizer_access_token").toString();
                }
            }
            throw new DataOverflowException(ErrorCode.ERR_WX_AAT_NULL);
        }
        throw new DataOverflowException(ErrorCode.ERR_APPID_NULL);
    }
}
